<template>
  <GlobalDrawer
    v-model="visible"
    :title="formTitle"
    size="80%"
    :show-footer-buttons="props.mode !== 'view'"
    @confirm="handleSubmit"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" v-loading="loading">
      <!-- 基础信息区域 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户" :prop="props.mode === 'view' ? undefined : 'customer_id'">
            <!-- 查看模式：纯文本显示 -->
            <div v-if="props.mode === 'view'" class="view-text">
              {{ selectedCustomerName || '未知客户' }}
            </div>
            <!-- 其他模式：表单控件 -->
            <template v-else>
              <!-- 从客户资料发起时，显示客户名称，不可编辑 -->
              <el-input
                v-if="props.customerId && !props.opportunityId"
                :value="selectedCustomerName || '加载中...'"
                disabled
                placeholder="客户名称"
                style="width: 100%"
              />
              <!-- 其他情况，支持远程搜索 -->
              <el-select
                v-else
                v-model="form.customer_id"
                placeholder="请输入关键词搜索客户"
                filterable
                remote
                reserve-keyword
                :remote-method="remoteSearchCustomer"
                :loading="customerSearchLoading"
                style="width: 100%"
                :disabled="!!props.opportunityId"
                @change="handleCustomerChange"
              >
                <el-option
                  v-for="item in customerOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="联系人" :prop="props.mode === 'view' ? undefined : 'contact_id'">
            <!-- 查看模式：纯文本显示 -->
            <div v-if="props.mode === 'view'" class="view-text">
              {{ getContactDisplay() }}
            </div>
            <!-- 其他模式：表单控件 -->
            <template v-else>
              <el-select
                v-model="form.contact_id"
                placeholder="请选择联系人"
                filterable
                style="width: 100%"
                :disabled="!form.customer_id"
                :loading="contactLoading"
              >
                <el-option
                  v-for="item in contactOptions"
                  :key="item.id"
                  :label="`${item.name} (${item.phone || '无电话'})`"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 机会详情区域 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发现日期" :prop="props.mode === 'view' ? undefined : 'discovery_date'">
            <!-- 查看模式：纯文本显示 -->
            <div v-if="props.mode === 'view'" class="view-text">
              {{ form.discovery_date || '-' }}
            </div>
            <!-- 其他模式：表单控件 -->
            <template v-else>
              <el-date-picker
                v-model="form.discovery_date"
                type="date"
                placeholder="请选择发现日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </template>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="类别" :prop="props.mode === 'view' ? undefined : 'category'">
            <!-- 查看模式：纯文本显示 -->
            <div v-if="props.mode === 'view'" class="view-text">
              {{ getOptionLabel(categoryOptions, form.category) || '-' }}
            </div>
            <!-- 其他模式：表单控件 -->
            <template v-else>
              <el-select v-model="form.category" placeholder="请选择类别" style="width: 100%">
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="等级" :prop="props.mode === 'view' ? undefined : 'level'">
            <!-- 查看模式：纯文本显示 -->
            <div v-if="props.mode === 'view'" class="view-text">
              {{ getOptionLabel(levelOptions, form.level) || '-' }}
            </div>
            <!-- 其他模式：表单控件 -->
            <template v-else>
              <el-select v-model="form.level" placeholder="请选择等级" style="width: 100%">
                <el-option
                  v-for="item in levelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                  <span style="float: left">{{ item.label }}</span>
                  <span style="float: right; color: #8492a6; font-size: 12px">
                    {{ item.probability }}
                  </span>
                </el-option>
              </el-select>
            </template>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="状态" :prop="props.mode === 'view' ? undefined : 'status'">
            <!-- 查看模式：纯文本显示 -->
            <div v-if="props.mode === 'view'" class="view-text">
              {{ getOptionLabel(statusOptions, form.status) || '-' }}
            </div>
            <!-- 其他模式：表单控件 -->
            <template v-else>
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 预期信息区域 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="预计签单日期" :prop="props.mode === 'view' ? undefined : 'expected_sign_date'">
            <!-- 查看模式：纯文本显示 -->
            <div v-if="props.mode === 'view'" class="view-text">
              {{ form.expected_sign_date || '-' }}
            </div>
            <!-- 其他模式：表单控件 -->
            <template v-else>
              <el-date-picker
                v-model="form.expected_sign_date"
                type="date"
                placeholder="请选择预计签单日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </template>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="预计金额(元)" :prop="props.mode === 'view' ? undefined : 'expected_amount'">
            <!-- 查看模式：纯文本显示 -->
            <div v-if="props.mode === 'view'" class="view-text">
              {{ formatAmount(form.expected_amount) }}
            </div>
            <!-- 其他模式：表单控件 -->
            <template v-else>
              <el-input-number
                v-model="form.expected_amount"
                :precision="2"
                :min="0"
                :step="1000"
                :controls="true"
                style="width: 100%"
                placeholder="请输入预计订单金额"
              />
            </template>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 详细信息区域 -->
      <el-form-item label="机会标题" :prop="props.mode === 'view' ? undefined : 'title'">
        <!-- 查看模式：纯文本显示 -->
        <div v-if="props.mode === 'view'" class="view-text">
          {{ form.title || '-' }}
        </div>
        <!-- 其他模式：表单控件 -->
        <template v-else>
          <el-input
            v-model="form.title"
            placeholder="请输入机会标题（如：XX公司法律顾问服务）"
            maxlength="100"
            show-word-limit
          />
        </template>
      </el-form-item>

      <el-form-item label="机会描述" :prop="props.mode === 'view' ? undefined : 'description'">
        <!-- 查看模式：纯文本显示 -->
        <div v-if="props.mode === 'view'" class="view-text pre-wrap">
          {{ form.description || '-' }}
        </div>
        <!-- 其他模式：表单控件 -->
        <template v-else>
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请详细描述客户需求、痛点、预算范围等关键信息"
            maxlength="500"
            show-word-limit
          />
        </template>
      </el-form-item>

      <el-form-item label="备注">
        <!-- 查看模式：纯文本显示 -->
        <div v-if="props.mode === 'view'" class="view-text pre-wrap">
          {{ form.remarks || '-' }}
        </div>
        <!-- 其他模式：表单控件 -->
        <template v-else>
          <el-input
            v-model="form.remarks"
            type="textarea"
            :rows="3"
            placeholder="其他备注信息"
            maxlength="200"
            show-word-limit
          />
        </template>
      </el-form-item>

      <!-- 状态为"已转化"时，显示转化信息 -->
      <el-form-item v-if="form.status === 2 && (props.mode === 'edit' || props.mode === 'view')" label="转化订单">
        <div v-if="props.mode === 'view'" class="view-text">
          {{ form.order_id ? `已转化为订单 #${form.order_id}` : '未关联订单' }}
        </div>
        <template v-else>
          <el-tag v-if="form.order_id" type="success">已转化为订单 #{{ form.order_id }}</el-tag>
          <el-tag v-else type="warning">未关联订单</el-tag>
        </template>
      </el-form-item>

      <!-- 状态为"已失效"时，显示失效原因 -->
      <el-form-item v-if="form.status === 3" label="失效原因" :prop="props.mode === 'view' ? undefined : 'lose_reason'">
        <!-- 查看模式：纯文本显示 -->
        <div v-if="props.mode === 'view'" class="view-text pre-wrap">
          {{ form.lose_reason || '-' }}
        </div>
        <!-- 其他模式：表单控件 -->
        <template v-else>
          <el-input
            v-model="form.lose_reason"
            type="textarea"
            :rows="3"
            placeholder="请输入机会失效的原因"
            maxlength="200"
            show-word-limit
          />
        </template>
      </el-form-item>
    </el-form>
  </GlobalDrawer>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch } from 'vue'
  import { ElMessage, FormInstance } from 'element-plus'
  import { opportunityApi } from '@/api/crm/opportunity'
  import { customerApi, contactApi } from '@/api/crm/index'
  import type { ApiResponse, ListResponse } from '@/types/crm'
  import GlobalDrawer from '@/components/common/GlobalDrawer.vue'

  // 类型定义
  interface Customer {
    id: number
    name: string
  }

  interface Contact {
    id: number
    name: string
    phone: string
  }

  interface OpportunityForm {
    customer_id: number
    contact_id: number | undefined
    discovery_date: string
    category: number
    level: number
    status: number
    expected_sign_date: string
    expected_amount: number | undefined
    title: string
    description: string
    remarks: string
    lose_reason: string
    order_id?: number
  }

  interface FormRule {
    required?: boolean
    message: string
    trigger: string | string[]
    validator?: (rule: any, value: any, callback: any) => void
    min?: number
    max?: number
  }

  interface FormRules {
    [key: string]: FormRule[]
  }

  // 表单初始值
  const INITIAL_FORM: OpportunityForm = {
    customer_id: 0,
    contact_id: undefined,
    discovery_date: '',
    category: 1,
    level: 3,
    status: 1,
    expected_sign_date: '',
    expected_amount: undefined,
    title: '',
    description: '',
    remarks: '',
    lose_reason: '',
  }

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    opportunityId: {
      type: Number,
      default: 0,
    },
    customerId: {
      type: Number,
      default: 0,
    },
    mode: {
      type: String,
      default: 'add', // add 或 edit
    },
  })

  const emit = defineEmits(['update:modelValue', 'success'])

  const visible = computed({
    get: () => props.modelValue,
    set: value => emit('update:modelValue', value),
  })

  const formRef = ref<FormInstance | null>(null)
  const loading = ref(false)
  const submitting = ref(false)
  const contactLoading = ref(false)
  const customerSearchLoading = ref(false)
  const selectedCustomerName = ref('')

  const form = reactive<OpportunityForm>({ ...INITIAL_FORM })

  const categoryOptions = [
    { value: 1, label: '案件委托' },
    { value: 2, label: '法务需求' },
    { value: 3, label: '法务专项' },
  ]

  const levelOptions = [
    { value: 1, label: 'A级 - 本月可签', probability: '80%' },
    { value: 2, label: 'B级 - 30天可签', probability: '50%' },
    { value: 3, label: 'C级 - 持续跟进', probability: '20%' },
  ]

  const statusOptions = [
    { value: 1, label: '有效' },
    { value: 2, label: '已转化' },
    { value: 3, label: '已失效' },
  ]

  const customerOptions = ref<Customer[]>([])
  const contactOptions = ref<Contact[]>([])

  const rules: FormRules = {
    customer_id: [{ required: true, message: '请选择客户', trigger: 'change' }],
    contact_id: [
      {
        required: true,
        message: '请选择联系人',
        trigger: 'change',
        validator: (rule: any, value: any, callback: any) => {
          if (value === undefined || value === null || value === '') {
            callback(new Error('请选择联系人'))
          } else {
            callback()
          }
        },
      },
    ],
    discovery_date: [{ required: true, message: '请选择发现日期', trigger: 'change' }],
    category: [{ required: true, message: '请选择机会类别', trigger: 'change' }],
    level: [{ required: true, message: '请选择机会等级', trigger: 'change' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    expected_sign_date: [{ required: true, message: '请选择预计签单日期', trigger: 'change' }],
    expected_amount: [
      { required: true, message: '请输入预计订单金额', trigger: 'blur' },
      {
        message: '金额不能为负数',
        validator: (rule: any, value: any, callback: any) => {
          if (value !== undefined && value < 0) {
            callback(new Error('金额不能为负数'))
          } else {
            callback()
          }
        },
        trigger: 'blur',
      },
    ],
    title: [
      { required: true, message: '请输入机会标题', trigger: 'blur' },
      { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' },
    ],
    description: [{ required: true, message: '请输入机会描述', trigger: 'blur' }],
    remarks: [{ max: 200, message: '备注长度不能超过 200 个字符', trigger: 'blur' }],
    lose_reason: [
      {
        message: '状态为"已失效"时，失效原因不能为空',
        validator: (rule: any, value: any, callback: any) => {
          if (form.status === 3 && !value) {
            callback(new Error('状态为"已失效"时，失效原因不能为空'))
          } else {
            callback()
          }
        },
        trigger: 'blur',
      },
    ],
  }

  // 表单标题
  const formTitle = computed(() => {
    if (props.mode === 'edit') {
      return '编辑销售机会'
    }
    return props.opportunityId ? '查看销售机会' : '新增销售机会'
  })

  // 远程搜索客户
  const remoteSearchCustomer = async (query: string) => {
    if (!query) {
      customerOptions.value = []
      return
    }

    customerSearchLoading.value = true
    try {
      const res = await customerApi.list({
        keyword: query,
        page: 1,
        limit: 20,
      }) as ApiResponse<ListResponse<Customer>>

      customerOptions.value = (res.data.list || [])
        .filter(item => item && item.id !== undefined && item.id !== null)
        .map(item => ({
          id: Number(item.id),
          name: item.name || `客户${item.id}`,
        }))
    } catch (error: any) {
      if (error?.code === 'ERR_CANCELED') {
        return
      }
      customerOptions.value = []
    } finally {
      customerSearchLoading.value = false
    }
  }

  // 处理客户变化
  const handleCustomerChange = async (customerId: number) => {
    form.contact_id = undefined
    if (customerId) {
      await getContactList(customerId)
    }
  }

  // 获取客户联系人列表
  const getContactList = async (customerId: number) => {
    if (!customerId) return

    contactLoading.value = true
    try {
      const res = await contactApi.list(customerId) as ApiResponse<Contact[]>

      if (res.code === 0) {
        // 过滤掉无效的联系人数据
        const validContacts = (res.data || [])
          .filter(item => item && item.id !== undefined && item.id !== null)
          .map(item => ({
            id: Number(item.id),
            name: item.name || '未知联系人',
            phone: item.phone || '',
          }))

        // 如果没有联系人，添加"无联系人"选项，id为0
        if (validContacts.length === 0) {
          contactOptions.value = [
            {
              id: 0,
              name: '无联系人',
              phone: '',
            },
          ]
          // 自动选择"无联系人"
          form.contact_id = 0
        } else {
          contactOptions.value = validContacts
        }
      } else {
        // 出错时也提供"无联系人"选项
        contactOptions.value = [
          {
            id: 0,
            name: '无联系人',
            phone: '',
          },
        ]
        form.contact_id = 0
      }
    } catch (error: any) {
      // 忽略请求取消错误（组件卸载时的正常行为）
      if (error?.code === 'ERR_CANCELED') {
        return
      }
      // 出错时也提供"无联系人"选项
      contactOptions.value = [
        {
          id: 0,
          name: '无联系人',
          phone: '',
        },
      ]
      form.contact_id = 0
    } finally {
      contactLoading.value = false
    }
  }

  // 获取机会详情
  const getOpportunityDetail = async () => {
    if (!props.opportunityId) return

    loading.value = true

    try {
      const res = (await opportunityApi.getOpportunityDetail({
        id: props.opportunityId,
      })) as unknown as ApiResponse<OpportunityForm & { customer_name?: string }>
      const data = res.data

      Object.keys(form).forEach(key => {
        const formKey = key as keyof OpportunityForm
        if (data[formKey] !== undefined) {
          // 处理日期字段
          if (formKey === 'discovery_date' || formKey === 'expected_sign_date') {
            if (data[formKey]) {
              // 时间戳转日期字符串
              const timestamp = Number(data[formKey])
              const date = new Date(timestamp * 1000)
              form[formKey] = date.toISOString().split('T')[0]
            } else {
              form[formKey] = ''
            }
          }
          // 处理数值字段（category、level、status是数字类型）
          else if (formKey === 'expected_amount') {
            if (data[formKey] !== null && data[formKey] !== undefined) {
              form[formKey] = Number(data[formKey])
            } else {
              ;(form as any)[formKey] = undefined
            }
          }
          // 处理数字类型字段（category, level, status, customer_id, contact_id等）
          else if (
            formKey === 'customer_id' ||
            formKey === 'contact_id' ||
            formKey === 'category' ||
            formKey === 'level' ||
            formKey === 'status'
          ) {
            if (data[formKey] !== null && data[formKey] !== undefined) {
              form[formKey] = Number(data[formKey])
            } else {
              ;(form as any)[formKey] = undefined
            }
          }
          else {
            // 其他字段直接赋值
            ;(form as any)[formKey] = data[formKey]
          }
        }
      })

      // 将当前客户添加到选项中（编辑模式需要显示客户名称）
      if (data.customer_name && form.customer_id) {
        customerOptions.value = [
          {
            id: form.customer_id,
            name: data.customer_name,
          },
        ]
        // 同时设置selectedCustomerName用于显示
        selectedCustomerName.value = data.customer_name
      }

      // 加载联系人列表
      if (form.customer_id) {
        await getContactList(form.customer_id)
      }
    } catch (error) {
      ElMessage.error('获取机会详情失败')
    } finally {
      loading.value = false
    }
  }

  // 获取客户名称（用于从客户资料发起时显示）
  const getCustomerName = async (customerId: number) => {
    try {
      const res = await customerApi.detail(customerId) as ApiResponse<Customer>
      if (res.data) {
        selectedCustomerName.value = res.data.name || `客户${customerId}`
      }
    } catch (error: any) {
      if (error?.code === 'ERR_CANCELED') {
        return
      }
      selectedCustomerName.value = `客户${customerId}`
    }
  }

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()

      submitting.value = true

      // 准备提交数据
      const submitData = {
        ...form,
        // 转换日期为时间戳
        discovery_date: form.discovery_date ? new Date(form.discovery_date).getTime() / 1000 : 0,
        expected_sign_date: form.expected_sign_date
          ? new Date(form.expected_sign_date).getTime() / 1000
          : 0,
      }

      if (props.opportunityId) {
        await opportunityApi.updateOpportunity({
          ...submitData,
          id: props.opportunityId,
        })
        ElMessage.success('更新成功')
      } else {
        await opportunityApi.addOpportunity(submitData)
        ElMessage.success('新增成功')
      }

      emit('success')
      handleClose()
    } catch (error) {
      // 表单验证失败时不显示错误提示
    } finally {
      submitting.value = false
    }
  }

  // 关闭对话框
  const handleClose = () => {
    if (formRef.value) {
      formRef.value.resetFields()
    }

    // 重置表单
    Object.assign(form, INITIAL_FORM)
    contactOptions.value = []
    customerOptions.value = []
    selectedCustomerName.value = ''

    visible.value = false
  }

  // 监听对话框显示
  watch(visible, async isVisible => {
    if (isVisible) {
      // 编辑模式时获取详情
      if (props.opportunityId) {
        await getOpportunityDetail()
      } else if (props.customerId) {
        // 新增模式，从客户资料发起，传入客户ID
        form.customer_id = props.customerId
        // 获取客户名称用于显示
        await getCustomerName(props.customerId)
        // 加载联系人列表
        await getContactList(props.customerId)
      }
    }
  })

  // 辅助函数：根据值获取选项标签
  const getOptionLabel = (options: any[], value: any): string => {
    if (value === undefined || value === null || value === '') return '-'
    const option = options.find(item => item.value === value)
    return option ? option.label : '-'
  }

  // 辅助函数：获取联系人显示文本
  const getContactDisplay = (): string => {
    if (!form.contact_id) return '-'
    const contact = contactOptions.value.find(item => item.id === form.contact_id)
    if (!contact) return '-'
    return `${contact.name} (${contact.phone || '无电话'})`
  }

  // 辅助函数：格式化金额显示
  const formatAmount = (amount: any): string => {
    if (amount === undefined || amount === null || amount === '') return '-'
    const num = Number(amount)
    if (isNaN(num)) return '-'
    return num.toFixed(2)
  }
</script>

<style scoped>
  .el-form {
    padding-right: 20px;
  }

  /* 查看模式下的纯文本样式 */
  .view-text {
    padding: 8px 12px;
    background-color: #f5f7fa;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    min-height: 32px;
    display: flex;
    align-items: center;
    color: #606266;
    font-size: 14px;
    line-height: 1.5;
    word-break: break-all;
  }

  /* 多行文本换行 */
  .pre-wrap {
    white-space: pre-wrap;
    word-break: break-word;
    padding: 8px 12px;
    background-color: #f5f7fa;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    min-height: 32px;
    color: #606266;
    font-size: 14px;
    line-height: 1.5;
  }
</style>
